package com.example.test4;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    Button btnBindService, btnUnbindService, btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind = false;

    // ServiceConnection用于监听Service的连接状态
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: 服务已连接");
            // 返回Service的Binder对象
            serviceBinder = (MyService.MyServiceBinder) service;
            isServiceBind = true; // 标记服务已绑定
            tvServiceStatus.setText("当前服务状态：已连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: 服务已断开");
            // 当Service异常终止时调用，正常解绑不会调用此方法
            isServiceBind = false; // 标记服务已解绑
            serviceBinder = null; // 清空Binder对象
            tvServiceStatus.setText("当前服务状态：已断开");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setStatusBarColor(getColor(R.color.purple_500));
        btnBindService = findViewById(R.id.btn_main_activity_bind_service);
        btnUnbindService = findViewById(R.id.btn_main_activity_unbind_service);
        btnGetStatus = findViewById(R.id.btn_main_activity_get_status);
        tvServiceStatus = findViewById(R.id.tv_main_activity_service_status);

        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);

        tvServiceStatus.setText("当前服务状态：未绑定");
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, MyService.class);

        int viewId = v.getId();
        if (viewId == R.id.btn_main_activity_bind_service) {
            // 如果service尚未绑定就绑定，如果已经绑定则忽略
            if (!isServiceBind) {
                Log.d(TAG, "onClick: 尝试绑定服务...");
                bindService(intent, conn, Context.BIND_AUTO_CREATE);
                // BIND_AUTO_CREATE 表示在绑定时如果服务尚未创建，则自动创建服务
            } else {
                Log.d(TAG, "onClick: 服务已经绑定，无需重复操作");
                Toast.makeText(this, "服务已经绑定", Toast.LENGTH_SHORT).show();
            }
        } else if (viewId == R.id.btn_main_activity_get_status) {
            // 如果service已经绑定，获取service的count计数并显示在界面上。
            if (isServiceBind && serviceBinder != null) {
                int count = serviceBinder.getCount();
                tvServiceStatus.setText("当前服务状态：计数 " + count);
                Log.d(TAG, "onClick: 获取服务状态，当前计数: " + count);
            } else {
                tvServiceStatus.setText("当前服务状态：未绑定或Binder为空");
                Log.d(TAG, "onClick: 服务未绑定或Binder为空，无法获取状态");
                Toast.makeText(this, "服务未绑定，请先绑定服务", Toast.LENGTH_SHORT).show();
            }
        } else if (viewId == R.id.btn_main_activity_unbind_service) {
            // 如果service已经绑定，则可以解绑，否则忽略
            if (isServiceBind) {
                Log.d(TAG, "onClick: 尝试解绑服务...");
                unbindService(conn);
                isServiceBind = false; // 标记服务已解绑
                serviceBinder = null; // 清空Binder对象
                tvServiceStatus.setText("当前服务状态：已解绑");
            } else {
                Log.d(TAG, "onClick: 服务尚未绑定，无需解绑");
                Toast.makeText(this, "服务尚未绑定", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保Activity销毁时解绑服务，防止内存泄漏
        if (isServiceBind) {
            Log.d(TAG, "onDestroy: Activity销毁，解绑服务");
            unbindService(conn);
            isServiceBind = false;
            serviceBinder = null;
        }
    }
}
